package org.example.common;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 创建该DateUtil类的目的是简化Date操作，封住常用Date方法！
 * 易错点：时区
 *
 **/

public class DateUtil {

    private Date date;

    public DateUtil(){
        this.date=new Date();
    }

    public DateUtil(long milliseconds){
        this.date=new Date(milliseconds);
    }

    public DateUtil(Date date){
        this.date=date;
    }

    public DateUtil(String date) throws ParseException {
        this.date= parse(date);
    }

    public static Date parse(String date) throws ParseException {
        SimpleDateFormat ft=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        return ft.parse(date);
    }

    /**
     * Date类型处理时间问题比较麻烦，比如想获取某年、某月、某星期，以及n天以后的时间，Date类虽然有getYear、getMonth等方法但都已经被弃用。
     * 构造参数，year-1900, month - 1
     * @param year
     * @param month
     * @param day
     * @param hours
     * @param minutes
     * @param seconds
     * @throws ParseException
     */

    @Deprecated
    public DateUtil(int year,int month,int day,int hours,int minutes,int seconds){
        this.date=new Date(year-1900,month-1,day,hours,minutes,seconds);
    }

    public long getTime(){
        return date.getTime();
    }

    public Date getDate(){
        return date;
    }

    public void setDate(Date date){
        this.date=date;
    }

    public String format(){
        return DateUtil.format(date);
    }

    public static String format(Date date){
        SimpleDateFormat ft=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        return ft.format(date);
    }

    public static String format(Date date,String pattern){
        SimpleDateFormat ft=new SimpleDateFormat(pattern);
        return ft.format(date);
    }

    public void add(int milliseconds){
        this.date=add(this.date,milliseconds);
    }

    public static Date add(Date date,int milliseconds){
        return new Date(date.getTime()+milliseconds);
    }

    public void substract(int millisecondes){
        this.date = substract(this.date,millisecondes);
    }

    public static Date substract(Date date,int milliseconds){
        return new Date(date.getTime());
    }

    public boolean isAfter(Date when){
        return date.after(when);
    }

    public boolean isBefore(Date when){
        return date.getTime()<when.getTime();
    }



}
